<template>
  <div class="container-account-div">
    <el-row :gutter="5">
      <el-col :span="4">
        <el-card>
          <div slot="header" class="clearfix">
            <span>组织机构</span>
            <el-button icon="el-icon-refresh" style="float: right; padding: 3px" type="text" @click="getDeptList"/>
          </div>
          <div class="text item">
            <el-tree
              :expand-on-click-node="false"
              :data="orgList"
              :props="defaultProps"
              default-expand-all
              @node-click="handleNodeClick"/>
          </div>
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-collapse-transition>
          <el-row v-show="searchShow" class="search-collapse">
            <el-form ref="searchForm" :model="formSearch" label-width="80px" size="small">
              <el-row :gutter="5">
                <el-col :span="8">
                  <el-form-item label="登录名称" prop="accountName">
                    <el-input v-model.trim="formSearch.accountName" placeholder="登录名称" clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="创建日期">
                    <el-date-picker
                      v-model="beginEndDate"
                      type="daterange"
                      size="small"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                      @change="beginEndDateChange"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="5">
                <el-col :span="6">
                  <el-form-item label="用户状态" prop="status">
                    <el-select v-model="formSearch.status" placeholder="用户状态">
                      <el-option label="所有" value=""/>
                      <el-option
                        v-for="item in dictOptions"
                        :key="item.dictCode"
                        :label="item.dictLabel"
                        :value="item.dictValue"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="手机号码" prop="phone">
                    <el-input v-model.trim="formSearch.phone" placeholder="手机号码" clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item>
                    <el-button type="primary" round icon="el-icon-search" @click="onSubmit">搜索</el-button>
                    <el-button type="reset" round icon="el-icon-refresh" @click="reset">重置</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-row>
        </el-collapse-transition>
        <el-row class="select-table">
          <el-row class="mb10">
            <el-col :span="20">
              <el-button v-permission="[&quot;system:account:add&quot;]" type="primary" icon="el-icon-plus" size="small" @click="handleAddUpdate()">新增</el-button>
              <el-button v-permission="[&quot;system:account:edit&quot;]" :disabled="isEditDisabled" type="warning" icon="el-icon-edit" size="small" @click="handleAddUpdate(mulSelection[0])">修改</el-button>
              <el-button v-permission="[&quot;system:account:deletebatch&quot;]" :disabled="isDeleteDisabled" type="danger" icon="el-icon-delete" size="small" @click="handleBatchDelete">删除</el-button>
            </el-col>
            <el-col :span="4">
              <el-button-group>
                <el-button icon="el-icon-search" size="small" @click="showSearch"/>
                <el-button icon="el-icon-refresh" size="small" @click="searchList"/>
                <el-dropdown :hide-on-click="false" trigger="click">
                  <el-button icon="el-icon-tickets" size="small"/>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                      <el-checkbox v-model="bIdColShow">用户编号</el-checkbox>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-checkbox v-model="bAccountNameColShow">登录名称</el-checkbox>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-checkbox v-model="bTrueNameColShow">真实姓名</el-checkbox>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-checkbox v-model="bOrgColShow">部门</el-checkbox>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-checkbox v-model="bPhoneColShow">手机号码</el-checkbox>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-checkbox v-model="bStatusColShow">状态</el-checkbox>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-checkbox v-model="bCreateTimeColShow">创建时间</el-checkbox>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <el-checkbox v-model="bToolColShow">操作</el-checkbox>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row>
            <el-table
              v-loading="tabLoading"
              :data="dataList"
              @selection-change="handleSelectionChange">
              <el-table-column
                type="selection"
                width="55"/>
              <el-table-column
                v-if="bIdColShow"
                prop="accountId"
                label="编号"
                width="80"/>
              <el-table-column
                v-if="bAccountNameColShow"
                prop="accountName"
                label="登录名称"
                width="80"/>
              <el-table-column
                v-if="bTrueNameColShow"
                prop="truename"
                label="真实姓名"
                width="80"/>
              <el-table-column
                v-if="bOrgColShow"
                prop="organizationId"
                label="部门"
                width="80">
                <template slot-scope="scope">
                  <span v-text="getDeptName(scope.row.organizationId)"/>
                </template>
              </el-table-column>
              <el-table-column
                v-if="bPhoneColShow"
                prop="phone"
                label="手机号码"
                width="110"/>
              <el-table-column
                v-if="bStatusColShow"
                prop="status"
                label="状态"
                width="80">
                <template slot-scope="scope">
                  <span
                    v-for="dictOption in dictOptions"
                    v-if="scope.row.status===dictOption.dictValue"
                    :key="dictOption.dictCode"
                    :class="['badge',dictOption.listClass]">{{ dictOption.dictLabel }}</span>
                </template>
              </el-table-column>
              <el-table-column
                v-if="bCreateTimeColShow"
                prop="createTime"
                label="创建时间"/>
              <el-table-column
                v-if="bToolColShow"
                label="操作"
                width="120">
                <template slot-scope="scope">
                  <el-tooltip content="修改用户" placement="top">
                    <el-button v-permission="[&quot;system:account:edit&quot;]" type="warning" icon="el-icon-edit" size="mini" circle @click="handleAddUpdate(scope.row)"/>
                  </el-tooltip>
                  <el-tooltip content="删除用户" placement="top">
                    <el-button v-permission="[&quot;system:account:delete&quot;]" type="danger" icon="el-icon-delete" size="mini" circle @click="handleDelete(scope.row)"/>
                  </el-tooltip>
                  <el-tooltip content="分配角色" placement="top">
                    <el-button v-permission="[&quot;system:account:grant&quot;]" type="success" icon="el-icon-circle-check-outline" size="mini" circle @click="handleGrant(scope.row)"/>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row class="mt10 fr">
            <el-pagination
              v-show="!tabLoading"
              :current-page="formSearch.pageNum"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="formSearch.pageSize"
              :total="total"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
          </el-row>
        </el-row>
      </el-col>
    </el-row>
    <!-- 部门设置 对话框 -->
    <addUpdate
      v-if="addUpdateFormVisible"
      ref="addUpdateDialog"
      @refreshDataList="searchList"/>
    <!-- 授权对话框 -->
    <grant v-if="grantDialogVisible" ref="grantDialog"/>
  </div>
</template>

<script>
import addUpdate from './add-update'
import grant from './grant'

import { getDictLabel } from '@/utils'

import resultCode from '@/utils/resultCode'
import { getDictByType } from '@/api/dict'
import { getList, deleteOne, deleteBatch } from '@/api/account'
import { getOrgList } from '@/api/org'

import permission from '@/directive/permission/index.js' // 权限判断指令
import checkPermission from '@/utils/permission' // 权限判断函数

// 表格动态错乱，可在el-table-column属性加上:key="Math.random()"
export default {
  name: 'Role',
  components: { addUpdate, grant },
  directives: { permission },
  data() {
    return {
      beginEndDate: null,
      searchShow: true,
      isEditDisabled: true,
      isDeleteDisabled: true,
      bOrgColShow: true,
      bStatusColShow: true,
      bPhoneColShow: true,
      bToolColShow: true,
      bIdColShow: true,
      bAccountNameColShow: true,
      bTrueNameColShow: true,
      bCreateTimeColShow: true,
      tabLoading: false,
      dictOptions: [],
      formSearch: {
        accountName: null,
        phone: null,
        orgIds: null,
        status: null,
        beginDate: null,
        endDate: null,
        pageNum: 1,
        pageSize: 10
      },
      orgList: [],
      orgArrayIds: [],
      total: null,
      dataList: [],
      mulSelection: [],
      addUpdateFormVisible: false,
      grantDialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getDictList()
    this.getDeptList()
    this.searchList()
  },
  methods: {
    checkPermission,
    beginEndDateChange: function() {
      console.log('=====beginEndDateChange=====')
      console.log(this.beginEndDate)
      if (this.beginEndDate) {
        this.formSearch.beginDate = this.beginEndDate[0]
        this.formSearch.endDate = this.beginEndDate[1]
      } else {
        this.formSearch.beginDate = null
        this.formSearch.endDate = null
      }
    },
    showSearch: function() {
      this.searchShow = !this.searchShow
    },
    getDictList: function() {
      getDictByType('sys_normal_disable').then(response => {
        const result = response.data// 请求接口返回的内容
        if (result.code === resultCode.SUCCESS) {
          this.dictOptions = result.data
          console.log('=========dictOptions=========')
          console.log(result.data)
        }
      })
    },
    searchList: function() {
      this.tabLoading = true
      getList(this.formSearch).then(response => {
        const result = response.data// 请求接口返回的内容
        if (result.code === resultCode.SUCCESS) {
          console.log('=========datalist=========')
          console.log(result.data)
          const page = result.data
          this.total = page.total
          this.dataList = page.list
        }
        this.tabLoading = false
      })
    },
    getDeptList: function() {
      this.formSearch.orgIds = null
      getOrgList('', '').then(response => {
        const result = response.data // 请求接口返回的内容
        if (result.code === resultCode.SUCCESS) {
          this.orgList = result.data
        }
      })
    },
    getDeptName: function(id) {
      const result = this.getOrgNameChild(this.orgList, id)
      return result
    },
    getOrgNameChild: function(orgArray, id) {
      let name = ''
      let bSearch = false
      if (orgArray && orgArray.length > 0) {
        orgArray.forEach(org => {
          if (org.id === id) {
            name = org.name
            bSearch = true
          }
        })
        if (bSearch) {
          return name
        } else {
          orgArray.forEach(org => {
            if (org.children && org.children.length > 0) {
              const n = this.getOrgNameChild(org.children, id)
              if (n !== '') {
                name = n
                return name
              }
            }
          })
        }
      }
      return name
    },
    handleNodeClick: function(data, node) {
      this.orgArrayIds = []
      this.handleCheckNodeChildIds(node)
      if (this.orgArrayIds && this.orgArrayIds.length > 0) {
        this.formSearch.orgIds = this.orgArrayIds.join(',')
      }
      this.searchList()
    },
    handleCheckNodeChildIds: function(node) {
      const id = node.data.id
      this.orgArrayIds.push(id)
      if (node.childNodes && node.childNodes.length > 0) {
        node.childNodes.forEach(child => {
          this.handleCheckNodeChildIds(child)
        })
      }
    },
    handleSelectionChange: function(val) {
      this.mulSelection = val
      console.log(this.mulSelection)
      console.log(val.length)

      if (this.mulSelection.length > 0) {
        this.isDeleteDisabled = false
        if (this.mulSelection.length == 1) {
          this.isEditDisabled = false
        } else {
          this.isEditDisabled = true
        }
      } else {
        this.isDeleteDisabled = true
        this.isEditDisabled = true
      }
    },
    onSubmit: function() {
      this.searchList()
    },
    reset: function() {
      this.$refs.searchForm.resetFields()
      this.beginEndDate = null
      this.formSearch.beginDate = null
      this.formSearch.endDate = null
    },
    handleSizeChange: function(val) {
      console.log('--------pageSize--' + val)
      this.formSearch.pageSize = val
      this.searchList()
    },
    handleCurrentChange: function(val) {
      console.log('--------pageNum--' + val)
      this.formSearch.pageNum = val
      this.searchList()
    },
    handleAddUpdate: function(row) {
      this.addUpdateFormVisible = true
      this.$nextTick(() => {
        this.$refs.addUpdateDialog.init(this.dictOptions, row)
      })
    },
    handleDelete: function(row) {
      this.$confirm('此操作将删除【' + row.accountName + '】用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOne(row.accountId).then(response => {
          const result = response.data// 请求接口返回的内容
          if (result.code === resultCode.SUCCESS) {
            this.$message.success('删除成功')
            this.searchList()
          }
        })
      }).catch(() => {

      })
    },
    handleGrant: function(row) {
      console.log('========row========')
      console.log(row.accountId)
      this.grantDialogVisible = true
      this.$nextTick(() => {
        this.$refs.grantDialog.init(row.accountId)
      })
    },
    handleBatchDelete: function() {
      let names = ''
      const ids = []
      this.mulSelection.forEach(row => {
        names += row.accountName + ' '
        ids.push(row.accountId)
      })
      console.log(ids)
      const strIds = ids.join(',')
      console.log('ids=' + strIds)
      this.$confirm('此操作将删除【' + names + '】用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBatch(strIds).then(response => {
          const result = response.data// 请求接口返回的内容
          if (result.code === resultCode.SUCCESS) {
            this.$message.success('删除成功')
            this.searchList()
          }
        })
      }).catch(() => {

      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'status') {
          return getDictLabel(v[j], this.dictOptions)
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style>
.container-account-div {
  padding: 10px 20px 10px 5px;
  height: 100%;
}
</style>
